<!--检测方案的添加修改组件-->
<template>
  <div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="65%"
      top="5vh"
      @close="handleClose"
      class="qc-template-dialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="localFormData"
        :rules="rules"
        label-width="100px"
        size="small"
        class="compact-form"
      >
        <!-- 方案基本信息 -->
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="方案编号" prop="template_code">
              <el-input
                v-model="localFormData.template_code"
                placeholder="请输入方案编号"
                :disabled="isSystemCode || isEditMode"
                size="mini"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4" v-if="!isEditMode">
            <el-switch
              v-model="isSystemCode"
              active-text="系统编号"
              inactive-text=""
              style="margin-top: 13px;"
              @change="handleSystemCodeChange"
            ></el-switch>
          </el-col>
          <el-col :span="12">
            <el-form-item label="方案名称" prop="template_name">
              <el-input
                v-model="localFormData.template_name"
                placeholder="请输入方案名称"
                size="mini"
                @blur="handleTemplateNameBlur"
                @input="handleTemplateNameInput"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="检测种类" prop="qc_types">
              <el-select
                ref="qcTypeSelect"
                v-model="localFormData.qc_types"
                placeholder="请选择检测种类"
                style="width: 100%"
                size="mini"
              >
                <el-option
                  v-for="item in normalizedQcTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用状态" prop="enable_flag">
              <el-radio-group v-model="localFormData.enable_flag" size="mini">
                <el-radio label="Y">启用</el-radio>
                <el-radio label="N">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input
            v-model="localFormData.remark"
            type="textarea"
            :rows="1"
            placeholder="请输入备注信息"
            size="mini"
          ></el-input>
        </el-form-item>
      </el-form>

      <!-- 列表切换标签 -->
      <div class="tab-switcher">
        <div
          class="tab-item"
          :class="{ active: activeTab === 'testItems' }"
          @click="activeTab = 'testItems'"
        >
          检测项
        </div>
        <div
          class="tab-item"
          :class="{ active: activeTab === 'materials' }"
          @click="activeTab = 'materials'"
        >
          {{ materialsTabTitle }}
        </div>
      </div>

      <!-- 检测项表格 - 只在编辑模式显示 -->
      <div class="table-section" v-if="isEditMode && activeTab === 'testItems'">
        <div class="section-header">
          <div class="action-buttons">
            <el-button size="mini" type="primary" @click="addTestItem">+ 新增</el-button>
            <el-button
              size="mini"
              type="warning"
              :disabled="selectedTestItems.length === 0"
              @click="batchEditTestItems"
            >
              ✅ 修改
            </el-button>
            <el-button
              size="mini"
              type="danger"
              :disabled="selectedTestItems.length === 0"
              @click="batchDeleteTestItems"
            >
              □ 删除
            </el-button>
          </div>
        </div>

        <el-alert
          v-if="testItems.length === 0 && !loading"
          type="info"
          title="暂无检测项数据"
          show-icon
          :closable="false"
          class="empty-alert"
          size="mini"
        >
          请点击"新增"按钮添加检测项
        </el-alert>

        <div v-loading="loading" class="table-container">
          <el-table
            :data="testItems"
            border
            size="mini"
            style="width: 100%"
            @selection-change="handleTestItemSelectionChange"
            v-show="testItems.length > 0"
            height="200"
          >
            <el-table-column type="selection" width="40"></el-table-column>
            <el-table-column prop="index_name" label="检测项名称" width="135"></el-table-column>
            <el-table-column prop="index_type" label="检测项类型" width="110">
              <template slot-scope="scope">
                {{ getInspectionItemTypeLabel(scope.row.index_type) }}
              </template>
            </el-table-column>
            <el-table-column prop="qc_tool" label="检测工具" width="110"></el-table-column>
            <el-table-column prop="check_method" label="检测要求" width="110"></el-table-column>
            <el-table-column prop="stander_val" label="标准值" width="100"></el-table-column>
            <el-table-column prop="unit" label="单位" width="100">

            </el-table-column>
            <el-table-column prop="threshold_max" label="误差上限" width="100"></el-table-column>
            <el-table-column prop="threshold_min" label="误差下限" width="100"></el-table-column>
            <el-table-column label="操作" width="110">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="editTestItem(scope.row)">修改</el-button>
                <el-button size="mini" type="text" @click="deleteTestItem(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 检测项表格中的分页 -->
        <div class="pagination-wrapper" v-if="testItemTotal > 0">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="testItemTotal"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="testItemPageSize"
            :current-page.sync="testItemCurrentPage"
            @size-change="handleTestItemPageSizeChange"
            @current-change="handleTestItemPageChange"
          />
        </div>
      </div>

      <!-- 物料产品表格 - 只在编辑模式显示 -->
      <div class="table-section" v-if="isEditMode && activeTab === 'materials'">
        <div class="section-header">
          <div class="action-buttons">
            <el-button size="mini" type="primary" @click="addMaterial">+ 新增</el-button>
            <el-button
              size="mini"
              type="warning"
              :disabled="showMaterialList ? selectedMaterials.length === 0 : selectedProducts.length === 0"
              @click="batchEditMaterials"
            >
              ✅ 修改
            </el-button>
            <el-button
              size="mini"
              type="danger"
              :disabled="showMaterialList ? selectedMaterials.length === 0 : selectedProducts.length === 0"
              @click="batchDeleteMaterials"
            >
              □ 删除
            </el-button>
          </div>
        </div>

        <!-- 物料列表 - 只在物料类型检测种类下显示 -->
        <template v-if="showMaterialList">
        <el-alert
          v-if="materials.length === 0 && !loading"
          type="info"
            title="暂无物料数据"
          show-icon
          :closable="false"
          class="empty-alert"
          size="mini"
        >
            请点击"新增"按钮添加物料
        </el-alert>

        <div v-loading="loading" class="table-container">
          <el-table
            :data="materials"
            border
            size="mini"
            style="width: 100%"
            @selection-change="handleMaterialSelectionChange"
            v-show="materials.length > 0"
            height="200"
          >
            <el-table-column type="selection" width="40"></el-table-column>
              <el-table-column prop="material_code" label="物料编码" width="120"></el-table-column>
              <el-table-column prop="material_name" label="物料名称" width="120">
              <template slot-scope="scope">
                {{ scope.row.material_name }}
              </template>
            </el-table-column>
            <el-table-column prop="material_sfn" label="规格型号" width="100"></el-table-column>
            <el-table-column prop="quantity_check_num" label="最低检测数" width="80"></el-table-column>
            <el-table-column prop="unit" label="单位" width="50"></el-table-column>
            <el-table-column prop="quantity_unqualified_num" label="最大不合格数" width="80"></el-table-column>
            <el-table-column prop="cr_rate" label="致命缺陷率" width="90"></el-table-column>
            <el-table-column prop="maj_rate" label="严重缺陷率" width="90"></el-table-column>
            <el-table-column prop="min_rate" label="轻缺陷率" width="90">
              <template slot-scope="scope">
                {{ scope.row.min_rate }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="editMaterial(scope.row)">修改</el-button>
                <el-button size="mini" type="text" @click="deleteMaterial(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 物料列表中的分页 -->
        <div class="pagination-wrapper" v-if="materialTotal > 0">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="materialTotal"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="materialPageSize"
            :current-page.sync="materialCurrentPage"
            @size-change="handleMaterialPageSizeChange"
            @current-change="handleMaterialPageChange"
          />
        </div>
        </template>

        <!-- 产品列表 - 只在产品类型检测种类下显示 -->
        <template v-else-if="showProductList">
          <el-alert
            v-if="products.length === 0 && !loading"
            type="info"
            title="暂无产品数据"
            show-icon
            :closable="false"
            class="empty-alert"
            size="mini"
          >
            请点击"新增"按钮添加产品
          </el-alert>

          <div v-loading="loading" class="table-container">
            <el-table
              :data="products"
              border
              size="mini"
              style="width: 100%"
              @selection-change="handleProductSelectionChange"
              v-show="products.length > 0"
              height="200"
            >
              <el-table-column type="selection" width="40"></el-table-column>
              <el-table-column prop="product_code" label="产品编码" width="120"></el-table-column>
              <el-table-column prop="product_name" label="产品名称" width="120">
                <template slot-scope="scope">
                  {{ scope.row.product_name }}
                </template>
              </el-table-column>
              <el-table-column prop="product_sfn" label="规格型号" width="100"></el-table-column>
              <el-table-column prop="quantity_check_num" label="最低检测数" width="80"></el-table-column>
              <el-table-column prop="unit" label="单位" width="50"></el-table-column>
              <el-table-column prop="quantity_unqualified_num" label="最大不合格数" width="80"></el-table-column>
              <el-table-column prop="cr_rate" label="致命缺陷率" width="90"></el-table-column>
              <el-table-column prop="maj_rate" label="严重缺陷率" width="90"></el-table-column>
              <el-table-column prop="min_rate" label="轻缺陷率" width="90">
                <template slot-scope="scope">
                  {{ scope.row.min_rate }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" @click="editProduct(scope.row)">修改</el-button>
                  <el-button size="mini" type="text" @click="deleteProduct(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 产品列表中的分页 -->
          <div class="pagination-wrapper" v-if="productTotal > 0">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="productTotal"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="productPageSize"
              :current-page.sync="productCurrentPage"
              @size-change="handleProductPageSizeChange"
              @current-change="handleProductPageChange"
            />
          </div>
        </template>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="confirmClose">取 消</el-button>
        <el-button size="mini" type="primary" @click="handleSubmit" :loading="submitting">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 检测项表单对话框 -->
    <test-item-form
      :visible.sync="testItemDialogVisible"
      :form-data="currentTestItem"
      :is-edit-mode="!!currentTestItem.record_id"
      @submit="handleTestItemSubmit"
    />

    <!-- 物料产品表单对话框 -->
    <material-form
      :visible.sync="materialDialogVisible"
      :form-data="currentMaterial"
      :is-edit-mode="!!currentMaterial.record_id"
      @submit="handleMaterialSubmit"
    />

    <!-- 产品表单对话框 -->
    <product-form
      :visible.sync="productDialogVisible"
      :form-data="currentProduct"
      :is-edit-mode="!!currentProduct.record_id"
      @submit="handleProductSubmit"
    />
  </div>
</template>

<script>
import axios from 'axios'
import request from '@/utils/request'
import TestItemForm from './TestItemForm.vue'
import MaterialForm from './MaterialForm.vue'
import ProductForm from './ProductForm.vue'
import {
  deleteQcTemplateIndex,
  deleteTemplateDetail,
  insertQcTemplate,
  updateQcTemplate,
  deleteQcTemplate,
  checkTemplateNameUnique,
  fetchMaterialList,
  fetchProductList
} from '@/api/qc/QualitySchemeOrder'
// 新增自动编号API导入
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers.js";

export default {
  components: {
    TestItemForm,
    MaterialForm,
    ProductForm
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    isEditMode: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      default: () => ({
        template_id: null,
        template_code: '',
        template_name: '',
        qc_types: '',
        enable_flag: 'Y',
        remark: ''
      })
    }
  },
  data() {
    return {
      activeTab: 'testItems',
      // 创建本地表单数据副本，避免直接修改props
      localFormData: {
        template_id: this.formData.template_id || null,
        template_code: this.formData.template_code || '',
        template_name: this.formData.template_name || '',
        qc_types: this.formData.qc_types ? String(this.formData.qc_types) : '',
        enable_flag: this.formData.enable_flag || 'Y',
        remark: this.formData.remark || ''
      },
      isSystemCode: true,
      qcTypeOptions: [
        { label: '自制工序检验', value: '1' },
        { label: '首检', value: '2' },
        { label: '巡检', value: '3' },
        { label: '来料检验', value: '4' },
        { label: '成品检验', value: '5' },
        { label: '生产退料检验', value: '6' },
        { label: '销售退货检验', value: '7' },
        { label: '出货检验', value: '8' }
      ],
      inspectionItemTypeOptions: [
        { label: '外观', value: '1' },
        { label: '视觉', value: '2' },
        { label: '尺寸', value: '3' },
        { label: '物理性能检测', value: '4' },
        { label: '化学成分检测', value: '5' }
      ],
      rules: {
        template_code: [
          { required: true, message: '请输入方案编号', trigger: 'blur' }
        ],
        template_name: [
          { required: true, message: '请输入方案名称', trigger: 'blur' },
          {
            validator: this.validateTemplateNameUnique,
            trigger: 'blur'
          }
        ],
        qc_types: [
          { required: true, message: '请选择检测种类', trigger: 'change' }
        ]
      },
      // 检测项相关数据
      testItems: [],
      selectedTestItems: [],
      testItemDialogVisible: false,
      testItemDialogTitle: '添加检测项',
      currentTestItem: {
        record_id: null,
        template_id: null,
        index_id: null,
        index_code: '',
        index_name: '',
        index_type: '',
        qc_tool: '',
        check_method: '',
        stander_val: '',
        unit: '',
        threshold_max: '',
        threshold_min: '',
        doc_url: '',
        remark: ''
      },
      testItemCurrentPage: 1,
      testItemPageSize: 10,
      testItemTotal: 0,
      // 物料相关数据
      materials: [],
      selectedMaterials: [],
      materialDialogVisible: false,
      materialDialogTitle: '添加物料',
      currentMaterial: {
        record_id: null,
        template_id: null,
        material_id: null,
        material_code: '',
        material_name: '',
        material_sfn: '',
        unit: '',
        quantity_check_num: 1,
        quantity_unqualified_num: 0,
        cr_rate: 0,
        maj_rate: 0,
        min_rate: 100,
        remark: ''
      },
      materialCurrentPage: 1,
      materialPageSize: 10,
      materialTotal: 0,
      // 产品相关数据
      products: [],
      selectedProducts: [],
      productDialogVisible: false,
      productDialogTitle: '添加产品',
      currentProduct: {
        record_id: null,
        template_id: null,
        product_id: null,
        product_code: '',
        product_name: '',
        product_sfn: '',
        product_unit: '',
        unit: '',
        quantity_check_num: 1,
        quantity_unqualified_num: 0,
        cr_rate: 0,
        maj_rate: 0,
        min_rate: 100,
        remark: ''
      },
      productCurrentPage: 1,
      productPageSize: 10,
      productTotal: 0,
      // 表单原始数据，用于比较是否修改
      originalFormData: {},
      originalTestItems: [],
      originalMaterials: [],
      originalProducts: [],
      loading: false,
      submitting: false,
      // 防抖定时器
      _validationTimer: null
    }
  },
  computed: {
    dialogTitle() {
      return this.isEditMode ? '编辑检测方案' : '添加检测方案'
    },
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    // 确保检测种类选项值类型一致
    normalizedQcTypeOptions() {
      return this.qcTypeOptions.map(item => ({
        ...item,
        value: String(item.value)
      }))
    },
    // 检测种类为物料的类型
    materialQcTypes() {
      return ['4', '6'] // 来料检验、生产退料检验
    },
    // 检测种类为产品的类型
    productQcTypes() {
      return ['1', '2', '3', '5', '8'] // 自制工序检验、首检、巡检、成品检验、出货检验
    },
    // 当前是否显示物料
    showMaterialList() {
      return this.materialQcTypes.includes(this.localFormData.qc_types)
    },
    // 当前是否显示产品
    showProductList() {
      return this.productQcTypes.includes(this.localFormData.qc_types)
    },
    // 物料产品标签页标题
    materialsTabTitle() {
      return this.showMaterialList ? '物料列表' : (this.showProductList ? '产品列表' : '物料产品')
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(val) {
        if (val) {
          // 延迟加载数据，避免立即触发验证
          this.$nextTick(() => {
            this.syncFormDataToLocal();
            this.loadData();
            
            // 如果是新增模式且启用了系统编号，则生成编号
            if (!this.isEditMode && this.isSystemCode) {
              this.generatePlanCode();
            }
          })
        } else {
          // 关闭对话框时重置数据
          this.resetTableData();
          // 清除防抖定时器
          if (this._validationTimer) {
            clearTimeout(this._validationTimer);
            this._validationTimer = null;
          }
        }
      }
    },
    // 同步外部传入的表单数据到本地
    formData: {
      deep: true,
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.syncFormDataToLocal();
        }
      }
    },
    // 监听本地检测种类变化
    'localFormData.qc_types': {
      handler(newVal, oldVal) {
        if (newVal !== oldVal && newVal) {
          console.log('检测种类变更为:', newVal);
          // 切换时清空物料和产品数据
          if (this.showMaterialList) {
            this.products = [];
          } else if (this.showProductList) {
            this.materials = [];
          }

          // 如果在编辑模式下，重新加载对应数据
          if (this.isEditMode && this.localFormData.template_id) {
            this.loadListByQcType();
          }
        }
      }
    }
  },
  beforeDestroy() {
    // 组件销毁时清理定时器
    if (this._validationTimer) {
      clearTimeout(this._validationTimer)
      this._validationTimer = null
    }
  },
  created() {
    // 初始化时如果是系统编号且不是编辑模式，则生成方案编号
    if (this.isSystemCode && !this.isEditMode) {
      this.generatePlanCode();
    }
  },
  methods: {
    // 添加同步外部表单数据到本地副本的方法
    syncFormDataToLocal() {
      if (!this.formData) return;

      // 创建深拷贝，避免引用问题
      const formCopy = JSON.parse(JSON.stringify(this.formData));

      // 确保qc_types是字符串类型
      if (formCopy.qc_types !== undefined && formCopy.qc_types !== null) {
        formCopy.qc_types = String(formCopy.qc_types);
      }

      // 更新本地表单数据
      this.localFormData = {
        template_id: formCopy.template_id || null,
        template_code: formCopy.template_code || '',
        template_name: formCopy.template_name || '',
        qc_types: formCopy.qc_types || '',
        enable_flag: formCopy.enable_flag || 'Y',
        remark: formCopy.remark || ''
      };

      // 记录日志，检查值是否正确
      console.log('同步后的检测种类:', this.localFormData.qc_types, typeof this.localFormData.qc_types);
    },

    getInspectionItemTypeLabel(value) {
      // 处理空值情况
      if (value === null || value === undefined || value === '') {
        return '';
      }

      // 调试输出
      console.log('检测项类型值:', value, typeof value);

      // 将值转换为字符串进行比较
      const strValue = String(value).trim();

      // 查找匹配项
      const type = this.inspectionItemTypeOptions.find(item =>
        String(item.value).trim() === strValue
      );

      // 返回找到的标签或原始值
      return type ? type.label : strValue;
    },

    // 加载数据
    async loadData() {
      // 确保localFormData.qc_types是字符串类型
      if (this.localFormData.qc_types !== undefined && this.localFormData.qc_types !== null) {
        this.localFormData.qc_types = String(this.localFormData.qc_types);
      }

      if (this.isEditMode && this.localFormData.template_id) {
        // 添加loading状态并生成随机参数，避免被视为重复请求
        this.loading = true;
        try {
          // 顺序执行，确保每个请求之间有时间间隔
          await this.fetchTestItems();

          // 请求之间添加延时，避免并发导致的重复提交问题
          await new Promise(resolve => setTimeout(resolve, 300));

          // 第二个请求使用不同的随机参数
          await this.loadListByQcType();

          // 再次确保qc_types是字符串类型（防止异步加载过程中被覆盖）
          if (this.localFormData.qc_types !== undefined && this.localFormData.qc_types !== null) {
            this.localFormData.qc_types = String(this.localFormData.qc_types);
          }

          // 调试信息
          console.log('当前qc_types:', this.localFormData.qc_types, typeof this.localFormData.qc_types);

          // 验证是否有匹配项
          const hasMatch = this.qcTypeOptions.some(item => item.value === this.localFormData.qc_types);
          console.log('是否存在匹配项:', hasMatch);

          if (!hasMatch) {
            console.warn(`没有找到qc_types=${this.localFormData.qc_types}的匹配项`);
            // 可以设置默认值或保持原样
          }
        } catch (err) {
          console.error('加载数据失败:', err);
          // 显示友好的错误信息
          if (err.message && err.message.includes('重复提交')) {
            this.$message.warning('操作过于频繁，请稍后再试');
          } else {
            this.$message.error('加载数据失败，请重试');
          }
        } finally {
          this.loading = false;
        }
      } else {
        // 新增模式下清空列表
        this.testItems = [];
        this.materials = [];
        this.products = [];
      }

      // 保存原始数据用于比较
      this.originalFormData = {...this.localFormData};
      this.originalTestItems = JSON.parse(JSON.stringify(this.testItems));
      this.originalMaterials = JSON.parse(JSON.stringify(this.materials));
      this.originalProducts = JSON.parse(JSON.stringify(this.products));

      // 清除所有验证提示，但不触发验证
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.clearValidate();
          // 延迟清除验证状态，避免立即触发验证
          setTimeout(() => {
            if (this.$refs.formRef) {
              this.$refs.formRef.clearValidate();
            }
          }, 100);
        }
      });
    },

    // 重置表格数据
    resetTableData() {
      this.testItemCurrentPage = 1
      this.materialCurrentPage = 1
      this.productCurrentPage = 1
      this.testItemTotal = 0
      this.materialTotal = 0
      this.productTotal = 0
      this.selectedTestItems = []
      this.selectedMaterials = []
      this.selectedProducts = []
    },

    // 验证方案名称唯一性
    async validateTemplateNameUnique(rule, value, callback) {
      // 输入为空的处理
      if (!value) {
        callback(new Error('请输入方案名称'));
        return;
      }

      // 编辑模式且名称未改变，直接通过验证
      if (this.isEditMode && value === this.originalFormData.template_name) {
        callback();
        return;
      }

      // 添加防抖机制，避免频繁调用API
      if (this._validationTimer) {
        clearTimeout(this._validationTimer);
      }

      this._validationTimer = setTimeout(async () => {
        try {
          // 添加随机参数避免缓存影响
          const timestamp = new Date().getTime();
          const random = Math.floor(Math.random() * 1000);
          const response = await checkTemplateNameUnique(`${value}?t=${timestamp}-${random}`);
          console.log('验证名称唯一性返回数据:', response);

          // 根据后端返回的数据格式进行判断
          if (response !== null && response !== undefined) {
            // 如果后端直接返回 true（布尔值），表示名称可以使用
            if (response === true) {
              callback();
            }
            // 如果后端直接返回 false（布尔值），表示名称不可用
            else if (response === false) {
              callback(new Error('方案名称已存在，请使用其他名称'));
            }
            // 如果后端返回对象格式，检查 data 字段
            else if (typeof response === 'object') {
              if (response.data === true || response.data === "true") {
                callback();
              } else if (response.data === false || response.data === "false") {
                callback(new Error('方案名称已存在，请使用其他名称'));
              } else {
                // 其他情况默认通过
                callback();
              }
            }
            // 其他情况，默认通过验证
            else {
              callback();
            }
          } else {
            // 如果 response 为 null 或 undefined，默认通过验证
            callback();
          }
        } catch (error) {
          // 错误情况下不阻止用户操作
          if (error.message && error.message.includes('重复提交')) {
            // 对于重复提交错误，静默处理
            console.warn('忽略重复提交错误:', error.message);
            callback();
          } else {
            // 其他错误记录日志但允许通过
            console.error('验证名称唯一性出错:', error);
            console.warn('验证名称唯一性失败，但允许继续操作');
            callback();
          }
        }
      }, 500); // 500ms防抖延迟
    },

    // 获取检测项列表
    async fetchTestItems() {
      try {
        this.loading = true
        const templateId = this.localFormData.template_id

        const response = await request({
          url: `/ldzl-qc/qc/qcTemplate/selectQcTemplateIndexList?template_id=${templateId}&pageNum=${this.testItemCurrentPage}&pageSize=${this.testItemPageSize}`,
          method: 'post',
          data: { template_id: templateId },
          headers: {
            'Content-Type': 'application/json'
          }
        })

        if (response) {
          this.testItems = response.rows || []
          this.testItemTotal = response.total || 0
          console.log('检测项数据加载成功:', this.testItems)
        } else {
          throw new Error(response.msg || '返回数据格式不正确')
        }
      } catch (error) {
        // 如果是重复提交错误，静默处理
        if (error.message && error.message.includes('重复提交')) {
          console.warn('忽略重复提交错误:', error.message);
          return;
        }
        console.error('获取检测项列表失败:', error)
        this.$message.error(`获取检测项列表失败: ${error.message}`)
        this.testItems = []
        this.testItemTotal = 0
      } finally {
        this.loading = false
      }
    },

    // 获取物料列表
    async fetchMaterials() {
      try {
        this.loading = true
        const templateId = this.localFormData.template_id

        const response = await request({
          url: `/ldzl-qc/qc/qcTemplate/selectQcTemplateProductList?template_id=${templateId}&pageNum=${this.materialCurrentPage}&pageSize=${this.materialPageSize}`,
          method: 'post',
          headers: {
            'Content-Type': 'application/json'
          }
        })

        if (response) {
          // 过滤出物料数据（有material_code的记录）
          this.materials = (response.rows || []).filter(item => item.material_code)
          this.materialTotal = response.total || 0
          console.log('物料数据加载成功:', this.materials)
        } else {
          throw new Error(response.msg || '返回数据格式不正确')
        }
      } catch (error) {
        // 如果是重复提交错误，完全跳过错误处理
        if (error.message && error.message.includes('重复提交')) {
          // 静默处理，不打印任何日志
          console.warn('忽略重复提交错误:', error.message);
          return
        }
        console.error('获取物料列表失败:', error)
        this.$message.error('获取物料列表失败: ' + error.message)
        this.materials = []
        this.materialTotal = 0
      } finally {
        this.loading = false
      }
    },

    // 获取产品列表
    async fetchProducts() {
      try {
        this.loading = true
        const templateId = this.localFormData.template_id

        const response = await request({
          url: `/ldzl-qc/qc/qcTemplate/selectQcTemplateProductList?template_id=${templateId}&pageNum=${this.productCurrentPage}&pageSize=${this.productPageSize}`,
          method: 'post',
          headers: {
            'Content-Type': 'application/json'
          }
        })

        if (response) {
          // 过滤出产品数据（有product_code的记录）
          this.products = (response.rows || []).filter(item => item.product_code)
          this.productTotal = response.total || 0
          console.log('产品数据加载成功:', this.products)
        } else {
          throw new Error(response.msg || '返回数据格式不正确')
        }
      } catch (error) {
        // 如果是重复提交错误，完全跳过错误处理
        if (error.message && error.message.includes('重复提交')) {
          // 静默处理，不打印任何日志
          console.warn('忽略重复提交错误:', error.message);
          return
        }
        console.error('获取产品列表失败:', error)
        this.$message.error('获取产品列表失败: ' + error.message)
        this.products = []
        this.productTotal = 0
      } finally {
        this.loading = false
      }
    },

    // 检测项相关方法
    addTestItem() {
      this.currentTestItem = {
        record_id: null,
        template_id: this.localFormData.template_id,
        index_id: null,
        index_code: '',
        index_name: '',
        index_type: '',
        qc_tool: '',
        check_method: '',
        stander_val: '',
        unit: '',
        threshold_max: '',
        threshold_min: '',
        doc_url: '',
        remark: ''
      }
      this.testItemDialogTitle = '添加检测项'
      this.testItemDialogVisible = true
    },

    editTestItem(item) {
      this.currentTestItem = {...item}
      this.testItemDialogTitle = '修改检测项'
      this.testItemDialogVisible = true
    },

    deleteTestItem(item) {
      this.$confirm('确定删除该检测项吗?', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          this.loading = true
          const response = await deleteQcTemplateIndex([item.record_id])

          if (response) {
            this.testItems = this.testItems.filter(i => i.record_id !== item.record_id)
            this.$message.success('删除成功')
          } else {
            throw new Error(response?.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除检测项失败:', error)
          this.$message.error(`删除失败: ${error.message}`)
        } finally {
          this.loading = false
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    batchDeleteTestItems() {
      if (this.selectedTestItems.length === 0) {
        this.$message.warning('请至少选择一项')
        return
      }

      this.$confirm(`确定删除选中的 ${this.selectedTestItems.length} 条检测项吗?`, '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          this.loading = true
          const ids = this.selectedTestItems.map(item => item.record_id)

          const response = await deleteQcTemplateIndex(ids)

          if (response) {
            this.testItems = this.testItems.filter(item => !ids.includes(item.record_id))
            this.selectedTestItems = []
            this.$message.success('批量删除成功')
          } else {
            throw new Error(response?.msg || '批量删除失败')
          }
        } catch (error) {
          console.error('批量删除检测项失败:', error)
          this.$message.error(`批量删除失败: ${error.message}`)
        } finally {
          this.loading = false
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    batchEditTestItems() {
      if (this.selectedTestItems.length !== 1) {
        this.$message.warning('请选择一条检测项进行修改')
        return
      }
      this.editTestItem(this.selectedTestItems[0])
    },

    handleTestItemSubmit(formData) {
      if (formData.record_id) {
        // 修改
        const index = this.testItems.findIndex(item => item.record_id === formData.record_id)
        if (index !== -1) {
          this.testItems.splice(index, 1, formData)
          this.$message.success('修改成功')
        }
      } else {
        // 新增
        formData.record_id = this.generateId()
        this.testItems.push(formData)
        this.$message.success('添加成功')
      }
      this.testItemDialogVisible = false
    },

    handleTestItemSelectionChange(val) {
      this.selectedTestItems = val
    },

    // 检测项页面切换
    handleTestItemPageChange(val) {
      this.testItemCurrentPage = val;
      this.fetchTestItems()
    },

    // 检测项每页条数变更
    handleTestItemPageSizeChange(val) {
      this.testItemPageSize = val;
      // 重置为第一页
      this.testItemCurrentPage = 1;
      this.fetchTestItems()
    },

    // 物料相关方法
    addMaterial() {
      if (this.showProductList) {
        this.addProduct()
      } else {
      this.currentMaterial = {
        record_id: null,
        template_id: this.localFormData.template_id,
        material_id: null,
        material_code: '',
        material_name: '',
        material_sfn: '',
        unit: '',
        quantity_check_num: 1,
        quantity_unqualified_num: 0,
        cr_rate: 0,
        maj_rate: 0,
        min_rate: 100,
        remark: ''
      }
      this.materialDialogTitle = '添加物料'
      this.materialDialogVisible = true
      }
    },

    editMaterial(item) {
      this.currentMaterial = {...item}
      this.materialDialogTitle = '修改物料'
      this.materialDialogVisible = true
    },

    deleteMaterial(item) {
      this.$confirm('确定删除该物料吗?', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          this.loading = true
          const response = await deleteTemplateDetail([item.record_id])

          if (response) {
            this.materials = this.materials.filter(i => i.record_id !== item.record_id)
            this.$message.success('删除成功')
          } else {
            throw new Error(response?.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除物料失败:', error)
          this.$message.error(`删除失败: ${error.message}`)
        } finally {
          this.loading = false
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    batchDeleteMaterials() {
      if (this.showProductList) {
        this.batchDeleteProducts()
      } else {
      if (this.selectedMaterials.length === 0) {
        this.$message.warning('请至少选择一项')
        return
      }

      this.$confirm(`确定删除选中的 ${this.selectedMaterials.length} 条物料吗?`, '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          this.loading = true
          const ids = this.selectedMaterials.map(item => item.record_id)

          const response = await deleteTemplateDetail(ids)

          if (response) {
            this.materials = this.materials.filter(item => !ids.includes(item.record_id))
            this.selectedMaterials = []
            this.$message.success('批量删除成功')
          } else {
            throw new Error(response?.msg || '批量删除失败')
          }
        } catch (error) {
          console.error('批量删除物料失败:', error)
          this.$message.error(`批量删除失败: ${error.message}`)
        } finally {
          this.loading = false
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
      }
    },

    batchEditMaterials() {
      if (this.showProductList) {
        this.batchEditProducts()
      } else {
      if (this.selectedMaterials.length !== 1) {
        this.$message.warning('请选择一条物料进行修改')
        return
      }
      this.editMaterial(this.selectedMaterials[0])
      }
    },

    handleMaterialSubmit(formData) {
      console.log('接收到MaterialForm提交的数据:', formData);
      
      if (formData.record_id) {
        // 修改
        const index = this.materials.findIndex(item => item.record_id === formData.record_id)
        if (index !== -1) {
          this.materials.splice(index, 1, formData)
          console.log('更新物料数据成功:', formData);
        } else {
          // 如果找不到对应记录，可能是新ID，添加到列表
          this.materials.push(formData)
          console.log('找不到对应记录ID，添加为新记录:', formData);
        }
      } else {
        // 新增
        // 不要在这里生成ID，使用后端返回的ID
        // formData.record_id = this.generateId()
        this.materials.push(formData)
        console.log('添加新物料数据:', formData);
      }
      
      // 刷新页面显示，确保在列表中显示最新数据
      this.$nextTick(() => {
        // 如果是最后一页或者列表为空，保持当前页
        // 否则可能需要重新计算分页
        if (this.materials.length > 0) {
          // 计算总页数
          const totalPages = Math.ceil(this.materials.length / this.materialPageSize);
          
          // 如果当前页大于总页数，调整到最后一页
          if (this.materialCurrentPage > totalPages) {
            this.materialCurrentPage = totalPages;
          }
          
          console.log('刷新物料列表完成，当前页:', this.materialCurrentPage, '总页数:', totalPages);
        }
      });
      
      // 关闭对话框
      this.materialDialogVisible = false
    },

    handleMaterialSelectionChange(val) {
      this.selectedMaterials = val
    },

    // 物料页面切换
    handleMaterialPageChange(val) {
      this.materialCurrentPage = val;
      this.fetchMaterials()
    },

    // 物料每页条数变更
    handleMaterialPageSizeChange(val) {
      this.materialPageSize = val;
      // 重置为第一页
      this.materialCurrentPage = 1;
      this.fetchMaterials()
    },

    // 产品相关方法
    addProduct() {
      this.currentProduct = {
        record_id: null,
        template_id: this.localFormData.template_id,
        product_id: null,
        product_code: '',
        product_name: '',
        product_sfn: '',
        product_unit: '',
        unit: '',
        quantity_check_num: 1,
        quantity_unqualified_num: 0,
        cr_rate: 0,
        maj_rate: 0,
        min_rate: 100,
        remark: ''
      }
      this.productDialogTitle = '添加产品'
      this.productDialogVisible = true
    },

    editProduct(item) {
      this.currentProduct = {...item}
      this.productDialogTitle = '修改产品'
      this.productDialogVisible = true
    },

    deleteProduct(item) {
      this.$confirm('确定删除该产品吗?', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          this.loading = true
          const response = await deleteTemplateDetail([item.record_id])

          if (response) {
            this.products = this.products.filter(i => i.record_id !== item.record_id)
            this.$message.success('删除成功')
          } else {
            throw new Error(response?.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除产品失败:', error)
          this.$message.error(`删除失败: ${error.message}`)
        } finally {
          this.loading = false
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    batchDeleteProducts() {
      if (this.selectedProducts.length === 0) {
        this.$message.warning('请至少选择一项')
        return
      }

      this.$confirm(`确定删除选中的 ${this.selectedProducts.length} 条产品吗?`, '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          this.loading = true
          const ids = this.selectedProducts.map(item => item.record_id)

          const response = await deleteTemplateDetail(ids)

          if (response) {
            this.products = this.products.filter(item => !ids.includes(item.record_id))
            this.selectedProducts = []
            this.$message.success('批量删除成功')
          } else {
            throw new Error(response?.msg || '批量删除失败')
          }
        } catch (error) {
          console.error('批量删除产品失败:', error)
          this.$message.error(`批量删除失败: ${error.message}`)
        } finally {
          this.loading = false
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    batchEditProducts() {
      if (this.selectedProducts.length !== 1) {
        this.$message.warning('请选择一条产品进行修改')
        return
      }
      this.editProduct(this.selectedProducts[0])
    },

    handleProductSubmit(formData) {
      console.log('接收到ProductForm提交的数据:', formData);
      
      if (formData.record_id) {
        // 修改
        const index = this.products.findIndex(item => item.record_id === formData.record_id)
        if (index !== -1) {
          this.products.splice(index, 1, formData)
          console.log('更新产品数据成功:', formData);
        } else {
          // 如果找不到对应记录，可能是新ID，添加到列表
          this.products.push(formData)
          console.log('找不到对应记录ID，添加为新记录:', formData);
        }
      } else {
        // 新增
        // 不要在这里生成ID，使用后端返回的ID
        // formData.record_id = this.generateId()
        this.products.push(formData)
        console.log('添加新产品数据:', formData);
      }
      
      // 刷新页面显示，确保在列表中显示最新数据
      this.$nextTick(() => {
        // 如果是最后一页或者列表为空，保持当前页
        // 否则可能需要重新计算分页
        if (this.products.length > 0) {
          // 计算总页数
          const totalPages = Math.ceil(this.products.length / this.productPageSize);
          
          // 如果当前页大于总页数，调整到最后一页
          if (this.productCurrentPage > totalPages) {
            this.productCurrentPage = totalPages;
          }
          
          console.log('刷新产品列表完成，当前页:', this.productCurrentPage, '总页数:', totalPages);
        }
      });
      
      // 关闭对话框
      this.productDialogVisible = false
    },

    handleProductSelectionChange(val) {
      this.selectedProducts = val
    },

    // 产品页面切换
    handleProductPageChange(val) {
      this.productCurrentPage = val;
      this.fetchProducts()
    },

    // 产品每页条数变更
    handleProductPageSizeChange(val) {
      this.productPageSize = val;
      // 重置为第一页
      this.productCurrentPage = 1;
      this.fetchProducts()
    },

    openDialog(templateId) {
      this.formData.template_id = templateId;
      this.dialogVisible = true;

      // 清除所有验证提示
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.clearValidate();
        }
      });
    },

    // handleAutoGenerateChange 已被 handleSystemCodeChange 替代

    // 处理方案名称输入变化
    handleTemplateNameInput() {
      // 当用户输入时，清除该字段的验证状态
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.clearValidate('template_name');
        }
      });
    },

    // 防抖函数
    _debounce(func, wait) {
      let timeout;
      return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(() => {
          func.apply(context, args);
        }, wait);
      };
    },

    // 处理方案名称失去焦点
    handleTemplateNameBlur() {
      // 使用防抖函数延迟验证，避免频繁调用API
      this._debounceValidate();
    },

    // 防抖验证函数
    _debounceValidate: function() {
      // 这里我们延迟500毫秒再验证，避免频繁调用API
      const delayValidate = this._debounce(function() {
        if (this.$refs.formRef) {
          this.$refs.formRef.validateField('template_name');
        }
      }, 500);

      delayValidate.call(this);
    },

    // 生成方案编号
    generatePlanCode() {
      getAutoNumbers(12).then(response => {
        if (response.code === 200) {
          this.localFormData.template_code = response.msg;
        } else {
          this.$message.error('获取方案编号失败');
        }
      }).catch(() => {
        this.$message.error('获取方案编号失败');
      });
    },
    
    // 处理系统编号开关变化
    handleSystemCodeChange(val) {
      if (val) {
        // 如果开启系统编号，则生成编号
        this.generatePlanCode();
      } else {
        // 如果关闭系统编号，则清空编号
        this.localFormData.template_code = '';
      }
    },

    // 通用方法
    generateId() {
      return Date.now() + Math.floor(Math.random() * 1000)
    },

    // 根据检测种类加载对应列表
    async loadListByQcType() {
      if (!this.localFormData.qc_types) return

      try {
        this.loading = true

        if (this.showMaterialList) {
          // 加载物料列表
          await this.fetchMaterials()
        } else if (this.showProductList) {
          // 加载产品列表
          await this.fetchProducts()
        }
      } catch (error) {
        // 如果是重复提交错误，静默处理
        if (error.message && error.message.includes('重复提交')) {
          console.warn('忽略重复提交错误:', error.message);
          return;
        }
        console.error('加载列表数据失败:', error)
        this.$message.error(`加载数据失败: ${error.message}`)
      } finally {
        this.loading = false
      }
    },

    // 检查表单是否有变更，需要考虑产品列表
    hasFormChanged() {
      // 检查主表单是否修改
      const formChanged = Object.keys(this.formData).some(
        key => this.formData[key] !== this.originalFormData[key]
      )

      // 检查检测项是否修改
      const testItemsChanged =
        this.testItems.length !== this.originalTestItems.length ||
        this.testItems.some((item, index) =>
          Object.keys(item).some(key =>
            item[key] !== this.originalTestItems[index]?.[key]
          )
        )

      // 检查物料是否修改
      const materialsChanged =
        this.materials.length !== this.originalMaterials.length ||
        this.materials.some((item, index) =>
          Object.keys(item).some(key =>
            item[key] !== this.originalMaterials[index]?.[key]
          )
        )

      // 检查产品是否修改
      const productsChanged =
        this.products.length !== this.originalProducts.length ||
        this.products.some((item, index) =>
          Object.keys(item).some(key =>
            item[key] !== this.originalProducts[index]?.[key]
          )
        )

      return formChanged || testItemsChanged || materialsChanged || productsChanged
    },

    confirmClose() {
      if (this.hasFormChanged()) {
        this.$confirm('表单内容已修改，确定要关闭吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.dialogVisible = false
        }).catch(() => {
          // 取消关闭
        })
      } else {
        this.dialogVisible = false
      }
    },

    handleClose() {
      // 清除所有验证提示
      if (this.$refs.formRef) {
        this.$refs.formRef.clearValidate();
      }
      this.$refs.formRef.resetFields();
      this.$emit('close');
    },

    // 提交表单
    handleSubmit() {
      // 验证表单
      this.$refs.formRef.validate(async valid => {
        if (!valid) return;

        // 进行名称唯一性检查
        if (!this.isEditMode && this.localFormData.template_name) {
          try {
            // 为防止缓存，添加时间戳
            const timestamp = new Date().getTime();
            const nameCheck = await checkTemplateNameUnique(`${this.localFormData.template_name}?t=${timestamp}`);

            // 根据后端返回的数据格式进行判断
            if (nameCheck !== null && nameCheck !== undefined) {
              // 如果后端直接返回 false（布尔值），表示名称不可用
              if (nameCheck === false) {
                this.$message.error('方案名称已存在，请使用其他名称');
                // 清除验证状态并重新验证该字段
                this.$nextTick(() => {
                  if (this.$refs.formRef) {
                    this.$refs.formRef.clearValidate('template_name');
                    this.$refs.formRef.validateField('template_name');
                  }
                });
                return;
              }
              // 如果后端返回对象格式，检查 data 字段
              else if (typeof nameCheck === 'object') {
                if (nameCheck.data === false || nameCheck.data === "false") {
                  this.$message.error('方案名称已存在，请使用其他名称');
                  // 清除验证状态并重新验证该字段
                  this.$nextTick(() => {
                    if (this.$refs.formRef) {
                      this.$refs.formRef.clearValidate('template_name');
                      this.$refs.formRef.validateField('template_name');
                    }
                  });
                  return;
                }
              }
            }
          } catch (error) {
            // 对于重复提交错误，允许继续操作
            if (error.message && error.message.includes('重复提交')) {
              console.warn('跳过重复验证，继续提交');
            } else {
              console.error('验证名称唯一性出错:', error);
              this.$message.error('验证名称唯一性出错');
              return;
            }
          }
        }

        try {
          this.submitting = true;

          // 如果启用了系统编号且不是编辑模式，在提交前获取最终编号
          if (this.isSystemCode && !this.isEditMode) {
            try {
              const response = await getAutoNumbersConsume(12);
              if (response && response.code === 200) {
                this.localFormData.template_code = response.msg;
              } else {
                this.$message.error('获取最终编号失败，请重试');
                this.submitting = false;
                return;
              }
            } catch (error) {
              this.$message.error('获取最终编号失败，请重试');
              this.submitting = false;
              return;
            }
          }

          // 准备提交数据，使用本地数据，根据检测种类决定提交物料还是产品
          const payload = {
            ...this.localFormData,
            test_items: this.testItems,
            materials: this.showMaterialList ? this.materials : this.products
          };

          console.log('准备提交的数据:', payload);

          let response;
          if (this.isEditMode) {
            // 修改质检方案
            response = await updateQcTemplate(payload);
          } else {
            // 新增质检方案
            response = await insertQcTemplate(payload);
          }

          if (response) {
            // 先通知父组件更新列表
            this.$emit('success');
            
            // 延迟显示成功消息和关闭对话框
            setTimeout(() => {
              this.$message.success(this.isEditMode ? '修改成功' : '新增成功');
            this.dialogVisible = false;
            // 清除验证状态
              if (this.$refs.formRef) {
            this.$refs.formRef.clearValidate();
              }
            }, 300);
          } else {
            throw new Error(response?.msg || '操作失败');
          }
        } catch (error) {
          console.error('提交失败:', error);
          this.$message.error(error.message || '操作失败');
        } finally {
          // 延迟重置提交状态，避免快速点击造成重复提交
          setTimeout(() => {
          this.submitting = false;
          }, 500);
        }
      });
    },

    // 删除整个质检方案
    deleteQcTemplate() {
      this.$confirm('确定删除该质检方案吗?', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          this.loading = true
          const response = await deleteQcTemplate([this.formData.template_id])

          if (response) {
            this.$message.success('删除成功')
            this.$emit('delete-success')
            this.dialogVisible = false
          } else {
            throw new Error(response?.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除质检方案失败:', error)
          this.$message.error(`删除失败: ${error.message}`)
        } finally {
          this.loading = false
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // async handleGenerateCode() 方法已被 generatePlanCode() 替代
  }
}
</script>

<style scoped>
/* 调整后的样式 */
.qc-template-dialog {
  max-height: 80vh;
  overflow-y: auto;
}

.compact-form .el-form-item {
  margin-bottom: 12px;
}

.compact-form .el-row {
  margin-bottom: 5px;
}

.tab-switcher {
  display: flex;
  margin: 10px 0;
  border-bottom: 1px solid #e6e6e6;
}

.tab-item {
  padding: 6px 15px;
  font-size: 13px;
  cursor: pointer;
  margin-right: 5px;
  border: 1px solid transparent;
  border-bottom: none;
  border-radius: 4px 4px 0 0;
  background-color: #f5f5f5;
}

.tab-item.active {
  background-color: #fff;
  border-color: #e6e6e6;
  border-bottom-color: #fff;
  color: #409EFF;
  font-weight: bold;
}

.tab-item:hover {
  color: #409EFF;
}

.action-buttons {
  margin-bottom: 8px;
}

.action-buttons .el-button {
  padding: 5px 8px;
  font-size: 12px;
}

.pagination-wrapper {
  display: flex;
  align-items: center;
  margin-top: 8px;
  padding: 5px 0;
  font-size: 12px;
}

.total-text {
  color: #606266;
  margin-right: 8px;
}

.page-size {
  color: #606266;
  margin-right: 10px;
}

.table-section {
  margin-top: 0;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 8px;
  background-color: #fff;
}

.section-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 8px;
}

.el-table {
  margin-top: 8px;
  font-size: 12px;
}

.table-container {
  min-height: 180px;
  position: relative;
}

.empty-alert {
  margin: 15px 0;
  padding: 8px 16px;
}

.dialog-footer {
  margin-top: 15px;
  text-align: right;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
}

.el-table .el-button--mini {
  padding: 4px 5px;
  font-size: 12px;
}

.el-pagination {
  padding: 0;
}

.el-pagination .btn-prev,
.el-pagination .btn-next,
.el-pagination .number {
  min-width: 24px;
  height: 24px;
  line-height: 24px;
  margin: 0 2px;
}

.el-input--mini .el-input__inner {
  height: 24px;
  line-height: 24px;
}
</style>
